﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace VerficationsWPF.HWControls
{
    /// <summary>
    /// 可以通过拖动控件，移动整个窗体。
    /// </summary>
    public class WindowDragger
    {
        FrameworkElement frameworkElement = default!;
        bool isLeftMouseDown = false;
        Point lastMousePosition = new Point();
        Point lastWindowPosition = new Point();

        /// <summary>
        /// 以目标制件初始化窗体拖动器。
        /// </summary>
        /// <param name="fe"></param>
        public WindowDragger(FrameworkElement fe)
        {
            frameworkElement = fe;
            frameworkElement.MouseDown += FrameworkElement_MouseDown;
            frameworkElement.MouseMove += FrameworkElement_MouseMove;
            frameworkElement.MouseUp += FrameworkElement_MouseUp;
        }

        private void FrameworkElement_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                try
                {

                    var win = Window.GetWindow(frameworkElement);
                    isLeftMouseDown = true;
                    lastMousePosition = frameworkElement.PointToScreen(Mouse.GetPosition(frameworkElement));
                    lastWindowPosition = new Point(win.Left, win.Top);
                }
                catch
                {
                    frameworkElement.MouseDown -= FrameworkElement_MouseDown;
                    frameworkElement.MouseMove -= FrameworkElement_MouseMove;
                    frameworkElement.MouseUp -= FrameworkElement_MouseUp;
                }
            }
        }
        private void FrameworkElement_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
        {
            if (isLeftMouseDown)
            {
                // 新的鼠标屏幕坐标
                var new_pos = frameworkElement.PointToScreen(Mouse.GetPosition(frameworkElement));

                Point offset = new Point(new_pos.X - lastMousePosition.X, new_pos.Y - lastMousePosition.Y);
                var win = Window.GetWindow(frameworkElement);
                win.Left = lastWindowPosition.X + offset.X;
                win.Top = lastWindowPosition.Y + offset.Y;
            }
        }

        private void FrameworkElement_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            isLeftMouseDown = false;
        }

    }
}
